<template>
    <div>
        <a-row>
            <a-col :xs="{ span: 19, offset: 0 }" :lg="{ span: 16, offset: 0 }">
                <a-input-search v-model="queryParams.position_name" placeholder="请输入职务名称" enter-button style="max-width: 300px;margin: 5px;" :allowClear="true"  autocomplete="off"/>

                <a-button type="primary" icon="search" style="margin: 5px;" @click="onSearch(false)">
                    查询
                </a-button>
                <a-button type="primary" icon="plus" style="margin: 5px;" @click="$refs.modal.add()">
                    新增
                </a-button>
                <a-button type="primary" icon="file-excel" style="margin: 5px;" @click="downloadTemplate">
                    模板下载
                </a-button>
                <a-upload
                    name="fileData"
                    :multiple="false"
                    :showUploadList="false"
                    accept=".xlsx"
                    :action="importActionUrl"
                    @change="handleImportChange"
                    style="margin:5px;">
                    <a-button type="primary"  :loading="uploading"> <a-icon type="upload" /> 批量导入 </a-button>
                </a-upload>
                <a-button type="primary" icon="cloud-download" style="margin:5px;" @click="exportBatchly">
                    批量导出
                </a-button>
            </a-col>
        </a-row>
        <br />
        <a-row>
            <a-col :xs="{ span: 22, offset: 0}" :lg="{span: 20, offset:2}">
                <a-table
                    :columns="columns"
                    :data-source="dataSource"
                    :pagination="false"
                    :footer="handleFooter"
                    rowKey="positionNo"
                    style="background-color: white"
                    :scroll="{ x: 800 }">
                    <span slot="action" slot-scope="text, record">
                        <a-icon type="edit" title="编辑" style="color: #178cf4" @click="$refs.modal.update(record)"/>
                      <a-divider type="vertical" />
                        <a-icon type="delete" title="删除" style="color: #178cf4" @click="handleDel(record.positionNo)"/>
                        <a-divider type="vertical" />
                        <a-icon type="appstore" title="授权" style="color: #178cf4" @click="showMenuTree(record)"/>
                    </span>
                </a-table>
            </a-col>
        </a-row>
        <create ref="modal" @ok="handleOk"></create>
        <a-modal v-model="showMenus" title="新增" @ok="authorization">
            <menu-tree ref="menus" :key="treeKey" :defaultChecked="defaultChecked"></menu-tree>
        </a-modal>
    </div>
</template>

<script>
import API from './api/api_cfg_position_integral';
import create from "@/modules/views/system/role/from/create.vue";
import menuTree from "@/components/menu/MenuTree.vue";
export default {
    components:{
        create,
        menuTree
    },
    data(){
        return {
            queryParams:{
                position_name:'',
                pageSize: 10,
                pageNum: 1
            },
            currentRow: null,
            columns: [
                {
                    title: '职务编码',
                    dataIndex: 'positionSign',
                    width: 200,
                },
                {
                    title: '职务名称',
                    dataIndex: 'positionName',
                    width: 200,
                },
                {
                    title: '月基础积分',
                    dataIndex: 'baseIntegral',
                    width: 200,
                },
                {
                    title: '每次互动积分',
                    dataIndex: 'signInScore',
                    width: 200,
                },
                {
                    title: '每次签到积分',
                    dataIndex: 'interaction',
                    width: 200
                },
                {
                    title: '操作',
                    width: 200,
                    scopedSlots: { customRender: 'action' },
                },
            ],
            dataSource: [],
            total:0,
            uploading: false,
            importActionUrl: window._CONFIG["apiURL"]+'/position/importData',
            showMenus: false,
            treeKey: new Date().getTime(),
            defaultChecked:[]
        }
    },
    methods:{
        handleFooter(currentPageData){
            return (<a-pagination v-model={this.queryParams.pageNum} total={this.total} show-less-items onChange={this.onSearch}/>)
        },
        onSearch(flag) {
            // 当前页改变时，传过来的是 pageNum, 不知道为社么, 很神奇
            if (!flag){
                this.queryParams.pageNum = 1;
            }
            API.page(Object.assign({},this.queryParams))
                .then(res => {
                    this.dataSource = res.list;
                    this.total = res.total;
                })
                .catch(e => {
                    console.log('查询职务数据出现错误...',e);
                    this.$message.error('数据查询异常,请联系管理员!');
                })
        },
        handleOk(){
            this.onSearch(false);
        },
        handleDel(id){
            let params = {
                id: id
            };
            API.remove(params).then(res =>{
                if (res.code === 0){
                    this.$message.success('删除成功');
                    this.onSearch(false);
                }else {
                    this.$message.error('删除失败,请联系管理员')
                }
            }).catch(e =>{
                this.$message.error('删除失败,请联系管理员')
            })

        },

        downloadTemplate(){
            let that = this;
            that.downloadLoading = true;
            API.getTemplateFile().then(
                function (result) {
                    if (result && parseInt(result.code) === 0) {
                        let fileName = result.templateFileName;
                        API.downloadFile(fileName).then(
                            function (res) {
                                let blob = new Blob([res], {type: "application/vnd.ms-excel"});
                                let downloadElement = document.createElement('a');
                                let href = URL.createObjectURL(blob);
                                downloadElement.href = href;
                                downloadElement.download = fileName;
                                document.body.appendChild(downloadElement);
                                downloadElement.click();
                                document.body.removeChild(downloadElement);
                                URL.revokeObjectURL(href);
                            }
                        );
                    }else{
                        that.$message.error('获取模板失败');
                    }
                },
                function (err) {
                    that.$message.error(err.toString());
                }
            ).finally(() =>{
                that.downloadLoading = false;
            })
        },
        exportBatchly(){
            let that = this;
            that.exportLoading = true;
            API.getExportFile(that.queryParams).then(
                function (result) {
                    if (result && parseInt(result.code) === 0) {
                        let fileName = result.exportFileName;
                        API.downloadFile(fileName).then(
                            function (res) {
                                let blob = new Blob([res], {type: "application/vnd.ms-excel"});
                                let downloadElement = document.createElement('a');
                                let href = URL.createObjectURL(blob);
                                downloadElement.href = href;
                                downloadElement.download = fileName;
                                document.body.appendChild(downloadElement);
                                downloadElement.click();
                                document.body.removeChild(downloadElement);
                                URL.revokeObjectURL(href);
                            }
                        );
                    }else{
                        that.$message.error('获取模板失败');
                    }
                },
                function (err) {
                    that.$message.error(err.toString());
                }
            ).finally(() =>{
                that.exportLoading = false;
            })
        },
        handleImportChange (info) {
            let that = this;
            if (info.file.status === 'uploading') {
                that.uploading = true;
                return;
            }
            that.uploading = false;
            if (info.file.status === 'done') {
                var resp = info.file.response;
                if(resp.code == 0){
                    that.$message.success(resp.msg);
                    that.onSearch(false);
                }else{
                    that.$message.error(resp.msg);
                }
            } else if (info.file.status === 'error') {
                that.$message.error('批量导入失败，服务器异常！');
            }
        },
        //授权
        showMenuTree(row){
            this.currentRow = row;
            this.treeKey= new Date().getTime();
            this.defaultChecked =row.menus? row.menus.split(','):[];
            this.showMenus = true;
        },
        authorization(){
            let that = this;
            if (!this.currentRow){
                this.$message.error('未获取到需授权用户,请联系管理员');
                return;
            }
            let menus = this.$refs.menus.checkedKeys.toString();
            let role = this.currentRow;
            role.menus = menus;

            API.update(role).then(res =>{
                if (res.code === 0){
                    that.$message.success('授权成功')
                    that.showMenus = false;
                }else {
                    that.$message.error('授权失败,请联系管理员')
                }
            }).catch(e =>{
                that.$message.error('授权失败,请联系管理员')
            })
        }
    },
    created() {
        this.onSearch(false);
    }
}
</script>

<style scoped>

</style>
